import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../app_files.dart';
import 'splash_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'dart:async';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flukit/flukit.dart';

class SplashWidget extends StatefulWidget {
  @override
  _SplashWidgetState createState() => _SplashWidgetState();
}

class _SplashWidgetState extends State<SplashWidget> {
  bool hadInit = false;

  SplashModel _splashModel;

  TimerUtil _timerUtil;

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  int _status = 0;
  int _count = 5;
  FileInfo info;

  final List<String> _guideList = [
    "images/1.jpg",
    "images/2.jpg",
    "images/3.jpg",
    "images/4.jpg",
    "images/5.jpg",
  ];

  List<Widget> _splashView = [];

//  @override
//  void didChangeDependencies() {
//    super.didChangeDependencies();
//    if (hadInit) {
//      return;
//    }
//    hadInit = true;
//
//    Navigator.pushReplacementNamed(context, 'home');
//    return;
//  }

  @override
  void initState() {
    super.initState();
    _init();
//    _initAsync();
  }

  _init() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String phone = prefs.getString(UserInfoConst.phone) ?? '';
    String password = prefs.getString(UserInfoConst.password) ?? '';
    if (password.length != 0 && phone.length != 0) {
      Navigator.pushReplacementNamed(context, 'home');
    }
    else {
      Navigator.pushReplacementNamed(context, 'login');
    }
  }

  _initAsync() async {
    final SharedPreferences prefs = await _prefs;


    String splash_model = prefs.getString('splash_model') ?? '';
    bool _keyGuide = prefs.getBool(ThemeConfig.key_guide) ?? true;
    if (_keyGuide) {
      prefs.setBool(ThemeConfig.key_guide, false);
      _initGuide();
      setState(() {
        _status = 2;
      });
    } else {
      if (splash_model.length != 0) {
        Map jsonStr = json.decode(splash_model);
        DefaultCacheManager manager = DefaultCacheManager();
        info = await manager.getFileFromCache(jsonStr['picname']);
        if (info != null) {
          _splashModel = SplashModel.fromJson(jsonStr);
          setState(() {});
        }
      }
      _initSplash();
    }
  }

  void _initSplash() {
    if (_splashModel == null) {
      _goMain();
    } else {
      _doCountDown();
    }
  }

  void _initGuide() {
    for (int i = 0, length = _guideList.length; i < length; i++) {
      if (i == length - 1)
        _splashView.add(Stack(
          children: <Widget>[
            Image.asset(
              _guideList[i],
              fit: BoxFit.fill,
              width: double.infinity,
              height: double.infinity,
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                margin: EdgeInsets.only(bottom: 100.0),
                child: InkWell(
                  onTap: () {
                    _goMain();
                  },
                  child: Container(
                    height: 100,
                    width: 200,
                    decoration: BoxDecoration(
                      color: Colors.transparent,
//                      borderRadius: BorderRadius.all(Radius.circular(25.0)),
                    ),
//                    child: Center(
//                      child: Padding(
//                        padding: EdgeInsets.only(bottom: 2),
//                        child: Text(
//                          '立即体验',
//                          textAlign: TextAlign.center,
//                          style: TextStyle(color: Colors.white, fontSize: 18.0),
//                        ),
//                      ),
//                    ),
                  ),
                ),
              ),
            ),
          ],
        ));
      else
        _splashView.add(Image.asset(
          _guideList[i],
          fit: BoxFit.fill,
          width: double.infinity,
          height: double.infinity,
        ));
    }
  }

  void _doCountDown() {
    setState(() {
      _status = 1;
    });
    _timerUtil = new TimerUtil(mTotalTime: 5 * 1000);
    _timerUtil.setOnTimerTickCallback((int tick) {
      double _tick = tick / 1000;
      setState(() {
        _count = _tick.toInt();
      });
      if (_tick == 0) {
        _goMain();
      }
    });
    _timerUtil.startCountDown();
  }

  Widget _buildSplashBg() {
    return Container(
      height: double.infinity,
      width: double.infinity,
      color: Colors.white,
//      child: SafeArea(
//          child: Column(
//        children: <Widget>[
//          Padding(
//            padding: EdgeInsets.only(top: 140),
//            child: Image.asset(
//              'images/logo.png',
//              width: 144,
//              height: 168,
//              fit: BoxFit.fill,
//            ),
//          ),
//          Padding(
//            padding: EdgeInsets.only(top: 50),
//            child: Image.asset(
//              'images/logo_name.png',
//              width: 144,
//              height: 37,
//              fit: BoxFit.fill,
//            ),
//          ),
//        ],
//      )),
    );
  }

  Widget _buildAdWidget() {
    if (_splashModel == null) {
      return new Container(
        height: 0.0,
      );
    }
    return new Offstage(
      offstage: !(_status == 1),
      child: new InkWell(
        onTap: () {
          _goMain();
          String url = CommonUtils.checkNullToString(_splashModel.url);
          if (url.length > 0) {
            CommonUtils.pushWebViewFlutterPage(context, '详情', url);
          } else {
//            CommonUtils.pushRoute(context, RoutePath.mallDetailView,
//                arguments: {"itemId": _splashModel.goodsID});
          }
        },
        child: Container(
          alignment: Alignment.center,
//          child :FadeInImage(
//            placeholder: FileImage(info.file),
//            image: FileImage(info.file),
//            width: double.infinity,
//            height: double.infinity,
//            fit: BoxFit.fill,
//          ),
          child: Image.file(
            info.file,
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.fill,
          ),
        ),
      ),
    );
  }

  void _goMain() {
    Navigator.pushReplacementNamed(context, 'home');
  }

  @override
  void dispose() {
    super.dispose();
    if (_timerUtil != null) _timerUtil.cancel(); //记得中dispose里面把timer cancel。
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: new Stack(
        children: <Widget>[
          new Offstage(
            offstage: !(_status == 0),
            child: _buildSplashBg(),
          ),
          _buildAdWidget(),
          new Offstage(
            offstage: !(_status == 1),
            child: new Container(
              alignment: Alignment.topRight,
              margin: EdgeInsets.only(top: 40, right: 20),
              child: InkWell(
                onTap: () {
                  _goMain();
                },
                child: new Container(
                    height: 30,
                    width: 75,
                    child: Center(
                      child: Text(
                        '$_count s跳过',
                        style: new TextStyle(
                            fontSize: 14.0, color: ThemeConfig.blackColor),
                      ),
                    ),
                    decoration: new BoxDecoration(
                      color: Color(0xFFF6F6F6),
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                    )),
              ),
            ),
          ),
          Offstage(
            offstage: !(_status == 2),
            child: _status == 2
                ? Swiper(
                    autoStart: false,
                    circular: false,
                    indicator: null,
                    children: _splashView)
                : Container(),
          ),
        ],
      ),
    );
  }
}
